<template>
  <div class="api-debug-container">
    <!-- Curl命令 -->
    <div v-if="currentApiDetail.path && currentApiDetail.method" class="section-title">Curl命令</div>
    <div v-if="currentApiDetail.path && currentApiDetail.method" class="curl-command">
      <pre>{{ generateCurlCommand(currentApiDetail) }}</pre>
      <button class="copy-btn" @click="copyToClipboard(generateCurlCommand(currentApiDetail))">复制</button>
    </div>
    
    <!-- Mock数据 -->
    <div class="section-title">Mock数据</div>
    <div class="api-form">
      <div class="form-group">
        <label class="form-label">Mock数据</label>
        <textarea id="mockData" class="form-textarea" readonly>{{ mockData }}</textarea>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" @click="generateMockData">生成Mock数据</button>
        <button class="btn btn-secondary" @click="copyToClipboard(mockData)">复制Mock数据</button>
      </div>
    </div>
    
    <!-- 在线测试 -->
    <div class="section-title">在线测试</div>
    <div class="api-form">
      <div class="form-group">
        <label class="form-label">请求URL</label>
        <input type="text" id="testUrl" class="form-input" :value="'http://localhost:8080' + currentApiDetail.path" readonly>
      </div>
      <div class="form-group">
        <label class="form-label">请求参数</label>
        <textarea id="testParams" class="form-textarea" v-model="testParams">{{ currentApiDetail.requestBody ? JSON.stringify(currentApiDetail.requestBody, null, 2) : '{}' }}</textarea>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" @click="sendTestRequest">发送请求</button>
      </div>
      <div id="testResult" v-if="showTestResult" style="margin-top: 20px;">
        <div class="response-container">
          <div class="response-header">响应结果</div>
          <div class="response-content">{{ testResult }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import type { ApiInfo, ApiHeader,SimpleApiInfo } from '../api/model';
import { ApiService } from '../api/services/apiService';

interface ApiDebugProps {
  currentApi: SimpleApiInfo;
}

const props = defineProps<ApiDebugProps>();
const currentApiDetail = ref<ApiInfo>({} as ApiInfo);

const mockData = ref('');
const showTestResult = ref(false);
const testResult = ref('');
const testParams = ref('');



// 监听currentApi变化，更新测试参数
watch(() => props.currentApi, async (newApi) => {
  if (newApi.id) {
    currentApiDetail.value = await ApiService.getApiDetail(newApi.id);
  }
});

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    showToast('内容已复制到剪贴板');
  } catch (err) {
    console.error('复制失败:', err);
    showToast('复制失败，请手动复制', 'error');
  }
};

const generateCurlCommand = (api: ApiInfo): string => {
  if (!api || !api.path || !api.method) {
    return '';
  }
  
  const method = api.method.toUpperCase();
  const url = `http://localhost:8080${api.path}`;
  let curlCommand = `curl -X ${method} "${url}"`;
  
  if (api.headers && Array.isArray(api.headers)) {
    api.headers.forEach((header: ApiHeader) => {
      if (header.name && header.value) {
        curlCommand += ` \
  -H "${header.name}: ${header.value}"`;
      }
    });
  }
  
  if (!api.headers || !api.headers.some((h: ApiHeader) => h.name?.toLowerCase() === 'content-type')) {
    curlCommand += ` \
  -H "Content-Type: application/json"`;
  }
  
  if (api.requestBody && ['POST', 'PUT', 'PATCH'].includes(method)) {
    try {
      const body = typeof api.requestBody === 'string' ? 
        api.requestBody : 
        JSON.stringify(api.requestBody);
      curlCommand += ` \
  -d '${body.replace(/'/g, "'\\''")}'`;
    } catch (e) {
      console.error('生成请求体失败:', e);
    }
  }
  
  return curlCommand;
};

const generateMockData = () => {
  const mockDataObj: Record<string, any> = {};

  
  mockData.value = JSON.stringify(mockDataObj, null, 2);
  showToast('Mock数据生成成功');
};

const sendTestRequest = () => {    
    showToast('测试请求失败', 'error');

};

const showToast = (message: string, type: 'success' | 'error' = 'success') => {
  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  toast.textContent = message;
  toast.style.position = 'fixed';
  toast.style.top = '20px';
  toast.style.right = '20px';
  toast.style.padding = '12px 20px';
  toast.style.borderRadius = '4px';
  toast.style.color = 'white';
  toast.style.backgroundColor = type === 'success' ? '#4CAF50' : '#f44336';
  toast.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
  toast.style.zIndex = '9999';
  toast.style.opacity = '0';
  toast.style.transition = 'opacity 0.3s ease';
  
  document.body.appendChild(toast);
  
  setTimeout(() => {
    toast.style.opacity = '1';
  }, 10);
  
  setTimeout(() => {
    toast.style.opacity = '0';
    setTimeout(() => {
      document.body.removeChild(toast);
    }, 300);
  }, 3000);
};
</script>

<style scoped>
/* 调试工具样式 */
.api-debug-container {
  width: 100%;
  padding: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin: 24px 0 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--border-color);
  color: var(--heading-color);
}

/* Curl命令样式 */
.curl-command {
  position: relative;
  background-color: var(--code-bg);
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.curl-command pre {
  margin: 0;
  overflow-x: auto;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  font-size: 13px;
  line-height: 1.5;
  color: var(--text-color);
}

.copy-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  font-size: 12px;
  background-color: var(--theme-color);
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.copy-btn:hover {
  opacity: 0.9;
}

/* 表单样式 */
.api-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--text-color);
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: var(--background-color);
  color: var(--text-color);
  font-size: 14px;
}

.form-textarea {
  min-height: 150px;
  resize: vertical;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
}

.form-textarea:read-only {
  background-color: var(--code-bg);
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 16px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn-primary {
  background-color: var(--theme-color);
  color: white;
}

.btn-primary:hover {
  opacity: 0.9;
}

.btn-secondary {
  background-color: var(--border-color);
  color: var(--text-color);
}

.btn-secondary:hover {
  background-color: var(--border-color-light);
}

/* 响应结果样式 */
.response-container {
  border: 1px solid var(--border-color);
  border-radius: 4px;
  overflow: hidden;
}

.response-header {
  padding: 12px;
  background-color: var(--background-color);
  border-bottom: 1px solid var(--border-color);
  font-weight: 500;
}

.response-content {
  padding: 12px;
  background-color: var(--code-bg);
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
  overflow-x: auto;
}
</style>